package asynqQueueClient

import (
	"gdshop-back-end-go/common/libs/asynqQueue"
	"github.com/gogf/gf/frame/g"
	"github.com/hibiken/asynq"
	"sync"
	"time"
)

var client *asynq.Client
var once sync.Once

// 初始化客户端
func initClient() {
	client = asynq.NewClient(
		asynqQueue.GetRedisClientOpt(),
	)
}

// GetClient 获取客户端，单例模式
func GetClient() *asynq.Client {
	once.Do(initClient)

	return client
}

func getOption(topic asynqQueue.OrderTopicType) []asynq.Option {
	switch topic {
	case asynqQueue.CloseNoPayOrder:
		tmp := g.Cfg().GetDuration("queue." + asynqQueue.OrderTopicName[topic] + ".delayTime")
		return []asynq.Option{
			asynq.ProcessIn(tmp * time.Second), // 多少秒后执行
			asynq.MaxRetry(3),                  // 最大重试次数
		}
	case asynqQueue.ConfirmOrder:
		tmp := g.Cfg().GetDuration("queue." + asynqQueue.OrderTopicName[topic] + ".delayTime")
		return []asynq.Option{
			asynq.ProcessIn(tmp * time.Second), // 多少秒后执行
			asynq.MaxRetry(3),                  // 最大重试次数
		}
	default:
		return []asynq.Option{
			asynq.ProcessIn(1 * time.Second), // 多少秒后执行
			asynq.MaxRetry(3),                // 最大重试次数
		}
	}
}

func GetTask(topic asynqQueue.OrderTopicType, payload []byte) *asynq.Task {
	return asynq.NewTask(asynqQueue.OrderTopicName[topic], payload, getOption(topic)...)
}
